import React, { useCallback, useEffect, useState } from 'react';
import { Modal, Row, Col } from 'antd';
import BuildTitle from '@/components/BuildTitle';

// import { UnControlled as CodeMirror  } from 'react-codemirror2';
import { UnControlled } from 'react-codemirror2';

import { ICode } from './type';

import 'codemirror/lib/codemirror.css';

import 'codemirror/theme/idea.css';

import 'codemirror/mode/sql/sql';
import 'codemirror/mode/shell/shell';
import 'codemirror/addon/display/placeholder';
import 'codemirror/addon/hint/show-hint.css'; // 用来做代码提示
import 'codemirror/addon/hint/show-hint.js'; // 用来做代码提示
import 'codemirror/addon/hint/sql-hint.js'; // 用来做代码提示

const CodeMirror: any = UnControlled;
export const NodeCodeEditor: React.FC<ICode> = ({
  title,
  onClose,
  onFormChange,
  defaultValue,
}) => {
  const className = 'class' + parseInt(String(Math.random() * 1000000));
  const modalTitle = (
    <BuildTitle title={title + '设置' ?? '弹窗'} className={className} />
  );

  const [editorValue, setEditorValue] = useState('');

  useEffect(() => {
    setEditorValue(defaultValue);
  }, [defaultValue]);

  const onEeditorChange = useCallback(
    (editor, data, value) => {
      setEditorValue(value);
    },
    [editorValue, defaultValue],
  );

  const onOk = () => {
    onFormChange(editorValue);
    onClose();
  };

  return (
    <Modal
      open={true}
      onCancel={onClose}
      className={className}
      title={modalTitle}
      width={1000}
      onOk={onOk}
    >
      <Row>
        <Col span={4}>{title}</Col>
        <Col span={20}>
          <div style={{ height: '300px' }}>
            <CodeMirror
              options={{
                mode: 'sql',
                theme: 'idea',
                lineNumbers: true,
              }}
              value={editorValue}
              onChange={onEeditorChange}
            />
          </div>
        </Col>
      </Row>
    </Modal>
  );
};
